package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.minio.MinioProperties;
import com.atguigu.lease.web.admin.service.FileService;
import io.minio.*;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


import java.io.InputStream;

import java.util.Date;
import java.util.UUID;

/**
 * @author Admin
 */
@Service
@EnableConfigurationProperties(MinioProperties.class)
public class FileServiceImpl implements FileService {


    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MinioProperties minioProperties;
    @Override
    public String uploadFile(MultipartFile file) {
        //上传图片到MinIo的代码
        try {

            // 判断指定的桶是否存在
            boolean found =
                    minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
            if (!found) {
                // 如果桶不存在，则创建新桶
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
            } else {
                System.out.println("Bucket 'lease' already exists.");
            }

            // 上传图片
            //1.获取源文件的名字  a.jpg
            String originalFilename = file.getOriginalFilename();
            //2.生成UUID作为文件的名字前缀
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            //3.获取当前日期，进行指定格式的格式化
            String format = DateFormatUtils.format(new Date(), "yyyy/MM/dd");
            //4.拼接生成唯一文件名
            String newFileName = format + "/" + uuid + "_" + originalFilename;


            //获取上传的图片的字节输入流
            InputStream inputStream = file.getInputStream();
            PutObjectArgs build = PutObjectArgs.builder()
                    //上传的对象是哪一个桶
                    .bucket(minioProperties.getBucketName())
                    //上传的对象在Minio存储的名字
                    .object(newFileName)
                    //上传对象的流
                    .stream(inputStream, inputStream.available(), -1)
                    .build();

            //上传图片
            minioClient.putObject(build);
            //http://192.168.141.100:9000/lease/ikun.jpg
            String url = minioProperties.getEndpoint() + "/" + minioProperties.getBucketName() + "/" + newFileName;
            return url;
        } catch (Exception e) {
            System.out.println("Error occurred: " + e);
        }
        return null;
    }
}
